package com.naver.jts;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Paint;
import java.awt.Rectangle;
import java.awt.geom.AffineTransform;
import java.util.ArrayList;
import java.util.List;

import javax.swing.JPanel;

import org.geotools.geometry.jts.Geometries;
import org.geotools.geometry.jts.LiteShape;

import com.vividsolutions.jts.geom.Envelope;
import com.vividsolutions.jts.geom.Geometry;

public class JTSDrawingPanel extends JPanel {
	private static final int MARGIN = 5;

	private List<Geometry> geometries = new ArrayList<Geometry>();
	private AffineTransform geomToScreen;

	public void addGeometry(Geometry geom) {
		geometries.add(geom);
	}

	@Override
	protected void paintComponent(Graphics g) {
		super.paintComponent(g);

		if (!geometries.isEmpty()) {
			setTransform();

			Graphics2D g2d = (Graphics2D)g;
//			Paint polyPaint = new GradientPaint(0, 0, Color.CYAN, 100, 100, Color.MAGENTA, true);
			Paint defaultPaint = Color.BLUE;

			for (Geometry geom : geometries) {
				LiteShape shape = new LiteShape(geom, geomToScreen, false);
				
				if (Geometries.get(geom) == Geometries.POLYGON) {
//					g2d.setPaint(polyPaint);
					g2d.setPaint(Color.RED);
					g2d.fill(shape);
				} else {
					g2d.setPaint(defaultPaint);
					g2d.draw(shape);
				}
			}
		}
	}

	private void setTransform() {
		Envelope env = getGeometryBounds();
		Rectangle visRect = getVisibleRect();
		Rectangle drawingRect = new Rectangle(visRect.x + MARGIN, visRect.y + MARGIN, visRect.width - 2 * MARGIN, visRect.height - 2 * MARGIN);

		double scale = Math.min(drawingRect.getWidth() / env.getWidth(), drawingRect.getHeight() / env.getHeight());
		double xoff = MARGIN - scale * env.getMinX();
		double yoff = MARGIN + env.getMaxY() * scale;
		geomToScreen = new AffineTransform(scale, 0, 0, -scale, xoff, yoff);
	}

	private Envelope getGeometryBounds() {
		Envelope env = new Envelope();
		for (Geometry geom : geometries) {
			Envelope geomEnv = geom.getEnvelopeInternal();
			env.expandToInclude(geomEnv);
		}

		return env;
	}
}